/**
 * 
 * TODO: 	add a method to compute average RTT of a given host.
 * 			add a method to determine the best host based on RTT and/or avg RTT
 * 
 */

package edu.ucla.multicastim.rtt;

import java.io.*;
import java.net.*;

public class SimpleRTTClient {

	boolean hostFound;
	boolean socketStatus;

	int [][] result;
	
	public void getRTT(String[] ip) throws IOException {

		// i = index of String[] ip
		// j = index of int array of RTT of one host
		// k = index of a RTT entry of a given host

		result = new int[ip.length][10];

		Socket socket = null;
		PrintWriter out = null;
		BufferedReader in = null;

		for (int i = 0; i < ip.length; i++) {

			try {
				socket = new Socket(ip[i], 55555);
				hostFound = true;

				out = new PrintWriter(socket.getOutputStream(), true);
				in = new BufferedReader(new InputStreamReader(socket
						.getInputStream()));
				socketStatus = true;
			} catch (UnknownHostException e) {
				System.err.println("Cannot find host: " + ip[i]);
				int ary[] = {1000000, 1000000, 1000000 };
				result[i] = ary;
				continue;
			} catch (IOException e) {
				System.err.println("Cannot setup socket with host: " + ip[i]);
				int ary[] = {1000000, 1000000, 1000000 };
				result[i] = ary;
				socketStatus = false;
				continue;
			}

			long start = 0;

			// records 10 RTTs for host i
			for (int j = 0; j < 10; j++) { // might want to change the order of
				// the next two lines
				start = System.currentTimeMillis();
				out.println("RTT");
				if (in.readLine().equals("RTT")) {
					result[i][j] = (int) (System.currentTimeMillis() - start);
				}
			}

			// notify server that we have gathered the RTT and that it can now
			// stop the current thread
			out.println("RTT OK");

			// print result to screen
			for (int j = 0; j < result[i].length; j++) {
				System.out.println("Host " + i + " (" + ip[i] + ") RTT: "
						+ result[i][j] + " milliseconds");
			}
		}

		if (socketStatus) {
			out.close();
			in.close();
		}

		if (hostFound) {
			socket.close();
		}
	}
	
	public int[][] getResult(){
		return result;
	}
}